import axios from 'axios';
import store from '@/store/index';
import router from '@/router';

// 创建axios实例
const service = axios.create({
  baseURL: process.env.VUE_APP_AMS_BASE_API + '/ams/api/v1',
  timeout: 5000, // 请求超时时间
  headers: {
    'Content-Type': 'application/json',
    'Accept': 'application/json'
  }
});

// request拦截器
service.interceptors.request.use(
  config => {
    /*
    const token = getToken();
    if (token) {
      config.headers['Authorization'] = 'Bearer ' + token;
    } else { // 如果 token 不存在，则直接打回登录页面
      store.dispatch('Clear').then(response => {
        router.replace({
          path: '/login',
        });
      }).catch(error => {
        console.log(error);
      });
    }
    */
    return config;
  },
  error => {
    // Do something with request error
    console.log(error); // for debug
    Promise.reject(error);
  }
);

// response 拦截器
service.interceptors.response.use(
  response => {
    return response;
  },error => {
    if (error.response) {
      switch (error.response.status) {
        case 401:
          store.dispatch('Clear').then(response => {
            router.replace({
              path: '/login',
            });
          });
          break;
        case 403:
          return Promise.reject(error);
      }
    } else {
      return Promise.reject(error);
    }
    return Promise.reject(error);
  }
);

export default service;
